package com.cskaoyan.utils;

import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class WdBeanUtil {
    public static <T> T transfer(Class<T> clazz, HttpServletRequest request) {
        // 获取参数Map
        Map<String, String[]> parameterMap = request.getParameterMap();
        try {
            // 获取无参构造器
            Constructor<T> constructor = clazz.getDeclaredConstructor();
            // 使用无参构造器实例化创建实例(对象)
            T instance = constructor.newInstance();
            // 调用BeanUtils来讲Map中的值封装给instance
            BeanUtils.copyProperties(instance,parameterMap);
            return instance;
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
